const ArticleColumn = require('../models/index/ArticleColumn')
const Column = require('../models/index/Column')
const Article = require('../models/index/Article')

// 创建文章
exports.createColumn = async function (ColumnObj) {
  const ins = await Column.create(ColumnObj)
  const data = ins.toJSON()
  return data
}

// 获取专栏列表
exports.getColumns = async function () {
  const result = await Column.findAll({
    include: [Article]
  })
  return JSON.parse(JSON.stringify(result))
}

// 删除专栏
exports.deleteColumn = async function (id) {
  const result = await Column.destroy({
    where: {
      id
    }
  })
  return result
}

// 更新专栏
exports.updateColumn = async function (id, ColumnObj) {
  const result = await Column.update(ColumnObj, {
    where: {
      id
    }
  })
  return result
}

// 查询专栏的所有文章
exports.getColumnById = async function (id) {
  const result = await Column.findByPk(id, {
    include: [Article]
  })
  if (result) {
    const articles = result.Articles
    articles.forEach((item) => {
      // 不返回关联的中间表
      delete item.dataValues.ArticleColumn
    })
    result.dataValues.list = articles
    result.dataValues.total = articles.length
    delete result.dataValues.Articles
    return result
  }
  return null
}

exports.deleteColumnConnectArticle = async function (columnId, articleId) {
  const result = await ArticleColumn.destroy({
    where: {
      ArticleId: articleId,
      ColumnId: columnId
    }
  })
  return result
}
